<template>
	<view class="layout">
		<view class="goBack" @click="goBack" :style="{top:(getStatusBarHeight()-2)+'px'}">
			<uni-icons type="back" color="#fff" size="20"></uni-icons>
		</view>
		<score-view :score="score" @tap="addScoreClick"></score-view>
		<view class="content">
			<view class="title">
				<view class="bg">
					<image src="../../static/bg_title.png" mode="aspectFill"></image>
					<image class="wallet" src="../../static/ic_wallet.png" v-if="false" mode="aspectFill"></image>
				</view>
				<view class="info" :style="{top:20+'px'}">
					<view class="title1">
						{{title}}
					</view>
					<view class="title2">
						{{itemNums}}次机会最高中奖金币数100万
					</view>
					<view class="title3">
						{{content}}
					</view>
				</view>
			</view>

			<view class="usernums" :style="{ height : numHeight + 'rpx'}">
				<view class="items">
					<view class="item" v-for="item in userNums"
						:style="{ border: item.isWin && isShowWin ? '2px solid red' : 'none' }">
						<view class="winnum">
							{{item.num}}
						</view>
						<view class="znum">
							{{item.pinyin}}
						</view>
						<view class="money">
							￥{{item.money}}
						</view>
					</view>
				</view>
				<canvas v-if="!isShowWin" class="canvas2" id="canvas2" canvas-id="canvas2" @touchstart="touchstart2"
					@touchmove="touchmove2" @touchend="touchend2"></canvas>
			</view>
			<view class="footer">

			</view>

		</view>
	</view>

	<uni-popup ref="resultPopup" :is-mask-click="false" mask-background-color="rgba(0,0,0,0.8)">
		<view class="resultPopup">
			<view class="bg win" v-if="winMoney !== 0">
				<view class="text">{{'恭喜您中得'+winMoney+'奖励'}}</view>
			</view>
			<view class="bg loser" v-else>
				<view class="text">{{'机会只留给有准备的人，\n再试一次吧！'}}</view>
			</view>
			<view class="submitBtn" @click="onSubmit">
				<button type="primary">再来一次</button>
			</view>
			
			<view class="close" @click="closeResult">
				<uni-icons type="close" color="#eee" size="40"></uni-icons>
			</view>
		</view>
	</uni-popup>

</template>

<script setup>
	import {
		ref
	} from "vue";
	import {
		getStatusBarHeight,
		getNavBarHeight,
		rpxToPx,
		pxToRpx
	} from "@/utils/system.js"

	import {
		onLoad,
		onShow,
		onReady
	} from "@dcloudio/uni-app"

	import {
		onMounted,
		getCurrentInstance
	} from 'vue'
import {onShareAppMessage,onShareTimeline} from "@dcloudio/uni-app";
import { getUserScore,SignInGetScore ,addUserScore} from "../../utils/common";
	const title = ref('');
	const titleHeight = ref(0)
	const numHeight = ref(0)
	const isShowWin = ref(false);
	const content = ref("刮开覆盖膜，如果出现数字\"7\"则获得该数字下的所示金额，如果出现数字\"77\"则获得该数字下的所示金额的两倍，如果出现数字\"777\"则获得该数字下的所示金额的三倍。");
	const tips = ref(
		' 设置奖项：￥10,000,000、￥5,000,000、￥2,000,000、￥1,000,000、￥500,000、￥100,000、￥50,000、￥10,000、￥1,000、￥500、￥200、￥100')

	const openNums = ref([])
	const userNums = ref([])

	const viewWidth = ref(0);
	const viewHeight = ref(0);
	const score = ref(0);
	const ctx = ref(null);

	

	const viewWidth2 = ref(0);
	const viewHeight2 = ref(0);
	const ctx2 = ref(null);

	const points = ref([]);
	const points2 = ref([]);
	
	const winPoints = ref(0);
	const userPoints = ref(0);
	const resultPopup = ref(null);
	let winMoney = ref(0);
	
	const itemNums = ref(0)
	// canvas示例对象
	const instance = getCurrentInstance()
	
	// 刮奖音效
	const innerAudioContext = uni.createInnerAudioContext();
	innerAudioContext.autoplay = false;
	innerAudioContext.src = "/static/audio/gua.m4a";

	function goBack() {
		// drawInit();
		uni.navigateBack({
			success: () => {
				
			},
			fail: () => {
				uni.reLaunch({
					url:'/pages/index/shouye'
				})
			}
		})
		
	}

	onLoad(e => {
		console.log(e);
		title.value = e.title;
		titleHeight.value = getStatusBarHeight() + 10;
		console.log(uni.getSystemInfoSync().screenHeight + ',' + uni.getSystemInfoSync().pixelRatio);

		numHeight.value = pxToRpx(uni.getSystemInfoSync().screenHeight - getNavBarHeight()) - (350+20)

		itemNums.value = Math.floor(numHeight.value / 120.0) * 5 ;
		console.log('itemNums:'+itemNums.value);
		creatNums();

	})
	
	//分享给好友
	onShareAppMessage((e)=>{
		return {
			title:"喜乐刮刮卡，你离百万富翁就差刮一刮",
			path:"/pages/index/shouye"
		}
	})
	
	//分享朋友圈
	onShareTimeline(()=>{
		return {
			title:"喜乐刮刮卡，你离百万富翁就差刮一刮",
			path:"/pages/index/shouye"
		}
	})
	
	onShow(()=>{
		score.value = getUserScore()
	})
	
	function addScoreClick(){
		score.value = SignInGetScore()
	}

	// 获取页面实例对象
	onMounted(() => {
		drawInit2();
		
	})

	function closeResult(){
		resultPopup.value.close();
	}
	
	function onSubmit(){
	  const myScore =	addUserScore(-50);
	  if(myScore>=0){
	  		  score.value = myScore;
	  		  resultPopup.value.close();
	  		   winMoney.value = 0;
	  		  // creatNums();
	  		  // drawInit2();
	  		 
	  		  isShowWin.value = false;
	  		  
	  		   ctx.value = null;
	  		   points.value = [];
	  		   ctx2.value = null;
	  		   points2.value = [];
	  		   winPoints.value = 0;
	  		   userPoints.value = 0;
	  }
	  setTimeout(()=>{
		  if(myScore>=0){
		  		  
		  		  creatNums();
		  		  drawInit2();
		  }
	  },500);
	 
	}

// https://mp-02da6b36-ab1b-494d-b346-d6763fb77772.cdn.bspapp.com/resource/guaguale/icon/1.png
	function creatNums() {
		let open = [7,77];
		let user = [];
		// 可以中两个数
		let isDoble = getRandomNum(110)>100;
		let isContainWin = false;
		while (user.length != itemNums.value) {
			const num = getRandomNum(120);
			if(open.includes(num)){
				if(!isContainWin){
					user.push(num)
					isContainWin = true;
				}else if(isDoble){
					user.push(num)
					isDoble = false;
				}
			}else{
				if(num<100){
					user.push(num)
				}
			}
		}

		openNums.value = [];
		for (let num in open) {
			const item = {
				num: padZero(open[num], 2),
				pinyin: getPinyinWithNum(open[num])
			}
			openNums.value.push(item);
		}

		userNums.value = [];
		for (let num in user) {
			// 中奖
			let money = "";
			let isWin = false;
			if (open.includes(user[num])) {
				money = getOnMony();
				if(user[num] == 7){
					winMoney.value += money;
				}else if(user[num] == 77){
					winMoney.value += money * 2;
				}else if(user[num] == 777){
					winMoney.value += money * 3;
				}
				isWin = true;
			} else {
				money = getOffMony()
			}
				
			const temp = user[num];
			const item = {
				num: padZero(temp, 2),
				pinyin: getPinyinWithNum(temp),
				money,
				isWin
			}
			userNums.value.push(item);
		}
	}

	// 获取未中奖金额
	function getOffMony() {
		// 概率 
		const moneys = [ 20 , 50, 100, 500, 1000, 10000, 50000, 100000, 500000, 1000000]
		const rate = getRandomNum(100);
		let level = 0;
		if (rate < 20) {
			level = 0
		} else if (rate < 30) {
			level = 1
		} else if (rate < 40) {
			level = 2
		} else if (rate < 50) {
			level = 3
		} else if (rate < 60) {
			level = 4
		} else if (rate < 70) {
			level = 5
		} else if (rate < 80) {
			level = 6
		} else if (rate < 90) {
			level = 7
		} else if (rate < 95) {
			level = 8
		} else if (rate <= 100) {
			level = 9
		} else {
			level = 0
		}

		return moneys[level]
	}

	
	// 获取中奖金额
	function getOnMony() {
		// 概率 
		const moneys = [20, 50, 100, 500, 1000, 10000, 50000, 100000, 500000, 1000000]
		const rate = getRandomNum(1000000);
		let level = 0;
		if (rate < 500000) { // 20
			level = 0
		} else if (rate < 800000) { // 50
			level = 1
		} else if (rate < 950000) { // 100
			level = 2
		} else if (rate < 970000) { // 500
			level = 3
		} else if (rate < 990000) { // 1000
			level = 4
		} else if (rate < 999000) { // 10000
			level = 5
		} else if (rate < 999900) { // 50000
			level = 6
		} else if (rate < 999955) { // 100000
			level = 7
		} else if (rate < 999998) { // 500000
			level = 8
		} else if (rate <= 1000000) { //1000000
			level = 9
		} else {
			level = 0
		}
	
		return moneys[level]
	}

	function getRandomNum(num) {
		return Math.floor(Math.random() * num) + 1;
	}

	function getPinyinWithNum(num) {
		const numToZh = ["LING", "YI", "ER", "SAN", "SI", "WU", "LIU", "QI", "BA", "JIU", "SHI"]
		if (num < 10) {
			return numToZh[0] + numToZh[num];
		} else {
			const shi = parseInt(num / 10);
			const ge = parseInt(num % 10);
			return numToZh[shi] + numToZh[ge];
		}
	}

	//数字前面加0
	function padZero(number, length) {
		return String(number).padStart(length, '0');
	}


	/*
		canvas2
	**/
	function touchstart2(e) {
		let startX = e.changedTouches[0].x;
		let startY = e.changedTouches[0].y;
		let startPoint = {
			x: startX,
			y: startY
		};
		//存点 一起画
		points2.value.push(startPoint);
		//每次触摸开始，开启新的路径F
		ctx2.value.beginPath();
	}

	let requestStatus = false;
	function touchmove2(e) {
		// innerAudioContext.pause()
		let moveX = e.changedTouches[0].x
		let moveY = e.changedTouches[0].y
		let movePoint = {
			x: moveX,
			y: moveY,
		}
		points2.value.push(movePoint)
		userPoints.value += 1
		if (points2.value.length >= 2) {
			drawLine2()
		}
		innerAudioContext.play();
		// if(!requestStatus){
		// 	requestStatus = true;
			
		// 	setTimeout(()=>{
		// 		// 模拟执行完毕
		// 		// 改变 requestStatus
		// 		requestStatus = false;
		// 	}, 100);
		// }
		
	}

	function touchend2(e) {

		points2.value = []

		chechShowAnwser()
	}

	function chechShowAnwser() {
		console.log(winPoints.value + ',' + userPoints.value);
		if ( userPoints.value >= 50) {
			isShowWin.value = true;
			setTimeout(() => {
				if(winMoney.value != 0){
					const innerAudioContext = uni.createInnerAudioContext();
					innerAudioContext.autoplay = false;
					innerAudioContext.src =
						"/static/audio/huanhu.mp3";
					innerAudioContext.play();
				}else{
					const innerAudioContext = uni.createInnerAudioContext();
					innerAudioContext.autoplay = false;
					innerAudioContext.src =
						"/static/audio/kexi.mp3";
					innerAudioContext.play();
				}
				resultPopup.value.open();
				score.value = addUserScore(winMoney.value)
			}, 500)
		} else {
			isShowWin.value = false;
		}

	}
	// 获取元素宽高
	function getViewHW2() {
		let info = uni.createSelectorQuery().in(instance).select(".usernums");
		console.log("info: ", info);
		return new Promise((resolve, reject) => {
			info.boundingClientRect((data) => {
				console.log("data: " + JSON.stringify(data));
				viewWidth2.value = data.width
				viewHeight2.value = data.height
				resolve()
			}).exec(function(res) {
				// 注意：exec方法必须执行，即便什么也不做，否则不会获取到任何数据
			})
		})
	}

	function drawLine2() {
		let point1 = points2.value[0]
		let point2 = points2.value[1]
		points2.value.shift()
		ctx2.value.moveTo(point1.x, point1.y)
		ctx2.value.lineTo(point2.x, point2.y)
		// ctx2.value.stroke()
		// ctx2.value.draw(true)
		
		ctx.value.clearRect(point2.x, point2.y, 100, 100);
	}
	
	async function drawInit2() {
		await getViewHW2()
		ctx2.value = uni.createCanvasContext('canvas2')
		let x = viewWidth2.value;
		let y = viewHeight2.value
		// let x = 400
		// let y = 400
		console.log(x, y);
		// 设置 globalCompositeOperation 为 "dissolve"
		// ctx.value.setGlobalCompositeOperation("dissolve");
		ctx2.value.setFillStyle('#bbb')
		ctx2.value.fillRect(0, 0, x, y)

		ctx2.value.setFontSize(30)
		ctx2.value.setTextBaseline('middle')
		ctx2.value.setFillStyle('black')
		ctx2.value.setTextAlign('center')
		ctx2.value.fillText(' 刮刮卡号码', x / 2, y / 2)
		// let image = uni.createSelectorQuery().in(instance).select(".wallet");
		// ctx2.value.drawImage(image,100,100);

		ctx2.value.lineWidth = 4;
		ctx2.value.lineCap = "round"
		ctx2.value.lineJoin = "round"
		ctx2.value.draw(true)
		
		//接下来线的样式
		// ctx2.value.lineWidth = 80; //刮的大小
		// ctx2.value.lineCap = "round"
		// ctx2.value.lineJoin = "round"
		// ctx2.value.setFillStyle('red')
		// ctx2.value.setStrokeStyle('red')
		// ctx2.value.globalCompositeOperation = 'destination-out' //关键是这个属性
	}
</script>

// <!-- // scss 语言类型  scoped css样式的类名仅限当前页面 不污染其它页面 -->
<style lang="scss">
	@font-face {
		font-family: NumFont;
		src: url('https://mp-02da6b36-ab1b-494d-b346-d6763fb77772.cdn.bspapp.com/resource/font/HONORSans-Bold.ttf');
	}

	.layout {
		width: 100%;
		height: 100vh;
		background-color: #008B8B;
		position: relative;

		.goBack {
			position: fixed;
			margin-left: 10rpx;
			width: 38px;
			height: 38px;
			background: rgba(0, 0, 0, 0.5);
			border-radius: 50%;
			backdrop-filter: blur(10rpx);
			border: 1rpx solid rgba(255, 255, 255, 0.3);
			display: flex;
			align-items: center;
			justify-content: center;
			z-index: 1000;
		}
		
		


		.content {
			// width: 100%;
			height: calc(100vh - 40rpx);
			background-color: #de3018;
			margin-top: 0rpx;
			border: 20rpx solid #008B8B;
			box-sizing: content-box;
			border-radius: 20px;
			overflow: hidden;
			position: relative;
			display: flex;
			align-items: center;
			flex-direction: column;

			.title {
				position: relative;
				width: 100%;

				.bg {
					position: absolute;
					top: 0rpx;
					left: 0rpx;
					width: 100%;
					height: 350rpx;

					image {
						width: 100%;
						height: 100%;
					}
				}

				.info {
					position: absolute;
					top: 0rpx;
					left: 0rpx;
					width: 100%;
					height: 350rpx;
					display: flex;
					align-items: center;
					flex-direction: column;

					.title1 {
						width: 100%;
						font-size: 110rpx;
						font-weight: bold;
						text-align: center;
						color: #008B8B;
						// color: white;
					}

					.title2 {
						width: 80%;
						font-size: 18px;
						text-align: center;
						color: #de3018;
						background-color: #ffe21d;
						padding: 0 20rpx;
					}

					.title3 {
						width: 100%;
						margin-top: 20rpx;
						font-size: 14px;
						text-align: center;
						color: #ffe21d;
						padding: 0 20rpx;
					}
				}
			}

			.usernums {
				margin-top: 420rpx;
				position: relative;
				width: 95%;
				background-color: #d8d7d7;
				border: 10rpx solid #008B8B;

				.items {
					width: 100%;
					display: grid;
					grid-template-columns: repeat(5, 1fr);
					row-gap: 10rpx;
					column-gap: 20rpx;
					padding: 5rpx;

					.item {
						width: 110rpx;
						height: 110rpx;
						// background-color: #d1d0d0;
						border-radius: 50%;

						.winnum {
							margin-top: 10rpx;
							font-size: 50rpx;
							text-align: center;
							color: #efefef;
							font-weight: bold;
							-webkit-text-stroke: 1px black;
							font-family: 'NumFont';
						}

						.znum {
							font-size: 16rpx;
							text-align: center;
							color: black;
							margin-top: -5rpx;
						}

						.money {
							font-size: 20rpx;
							text-align: center;
							color: black;
							font-weight: bold;
							margin-top: 0rpx;
						}
					}
				}

				.canvas2 {
					position: absolute;
					left: 0;
					top: 0;
					width: 100%;
					height: 100%;
				}

			}

		}
	}


	.resultPopup {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding-bottom: 150rpx;

		.bg {
			background: no-repeat center;
			background-size: cover;
			position: relative;
		}

		.win {
			width: 735rpx;
			height: 986rpx;
			background-image: url('https://mp-02da6b36-ab1b-494d-b346-d6763fb77772.cdn.bspapp.com/resource/image/bg_win_2.png');
			background-size:500rpx 655rpx ;
			.text {
				line-height: 120rpx;
				text-align: center;
				position: absolute;
				width: 100%;
				top: 605rpx;
				left: 0;
				color: #fff;
				font-size: 46rpx;
				font-weight: bolder;
			}
		}

		.loser {
			width: 735rpx;
			height: 986rpx;
			background-image: url('https://mp-02da6b36-ab1b-494d-b346-d6763fb77772.cdn.bspapp.com/resource/image/bg_lose_2.png');
			background-size:500rpx 605rpx ;
			.text {
				line-height: 80rpx;
				text-align: center;
				position: absolute;
				padding: 0 160rpx;
				width: 100%;
				top: 545rpx;
				left: 0;
				color: #fff;
				font-size: 40rpx;
				font-weight: bolder;
			}
		}
		.submitBtn{
			width: 60%;
			margin-top: -120rpx;
			button{
				background: #ee4626;
			}
		}

		.close {
			position: absolute;
			margin-left: 10rpx;
			width: 38px;
			height: 38px;
			// background: rgba(0, 0, 0, 0.5);
			border-radius: 50%;
			backdrop-filter: blur(10rpx);
			// border: 1rpx solid rgba(255, 255, 255, 0.3);
			display: flex;
			align-items: center;
			justify-content: center;
			z-index: 1000;
			right: 100rpx;
			top: 200rpx;
		}
	}
</style>